package cn.jingyuan.swan.gw.web.filter;

import cn.jingyuan.bee.spring.utils.WebUtils;
import cn.jingyuan.swan.gw.manager.AccessCheckManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Servlet filter：访问检查
 * <pre>
 *     1、资源允许公开访问
 *     2、资源状态是否正确
 * </pre>
 */
@Slf4j
public class AccessCheckFilter extends OncePerRequestFilter {

    AccessCheckManager accessCheckManager;

    AccessDeniedHandler accessDeniedHandler;

    public AccessCheckFilter(AccessCheckManager accessCheckManager, AccessDeniedHandler accessDeniedHandler) {
        this.accessCheckManager = accessCheckManager;
        this.accessDeniedHandler = accessDeniedHandler;
    }

    @Override
    protected void doFilterInternal(
        HttpServletRequest request,
        HttpServletResponse response,
        FilterChain filterChain
    ) throws ServletException, IOException {
        String path = accessCheckManager.getRequestPath(request);
        String remoteIpAddress = WebUtils.getRemoteAddress(request);
        String origin = request.getHeader(HttpHeaders.ORIGIN);

        /*
            1、验证资质是否允许公开访问
            2、验证资源状态是否正确
            3、ip 限制策略
         */

        // AuthorityResourceDto authorityResource = accessCheckManager.getResource(path);
        // if (null != authorityResource) {
        //
        // }


        filterChain.doFilter(request, response);
    }

}
